<template>
	<view class="buy-btn-container">
		<button @click="open" class="buy-btn">
			<text>立即预定</text>
		</button>
		<uni-popup ref="popup" type="bottom" :mask-click="false">
			<view class="popup-info">
				<view class="popup-header">
					<text class="popup-title">选择门票</text>
					<uni-icons type="close" size="24" color="#999" @click="close"></uni-icons>
				</view>
				
				<!-- 门票选择 -->
				<view class="ticket-section">
					<text class="section-title">门票类型</text>
					<view class="ticket-list">
						<view 
							v-for="ticket in availableTickets" 
							:key="ticket.ticketId"
							class="ticket-item"
							:class="{ active: selectedTickets.includes(ticket.ticketId) }"
							@click="toggleTicket(ticket)"
						>
							<view class="ticket-info">
								<text class="ticket-name">{{ getTicketTypeName(ticket.ticketType) }}</text>
							</view>
							<view class="ticket-price">
								<text class="price">¥{{ ticket.price }}</text>
								<text class="stock">库存: {{ ticket.stock }}</text>
							</view>
							<!-- 数量选择 -->
							<view class="ticket-quantity-control" v-if="selectedTickets.includes(ticket.ticketId)">
								<button class="quantity-btn" @click.stop="decreaseQuantity(ticket.ticketId)" :disabled="getTicketQuantity(ticket.ticketId) <= 1">-</button>
								<text class="quantity-text">{{ getTicketQuantity(ticket.ticketId) }}</text>
								<button class="quantity-btn" @click.stop="increaseQuantity(ticket.ticketId)" :disabled="getTicketQuantity(ticket.ticketId) >= ticket.stock">+</button>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 支付方式选择 -->
				<view class="payment-section" v-if="selectedTickets.length > 0">
					<text class="section-title">支付方式</text>
					<view class="payment-list">
						<view 
							v-for="payment in paymentMethods" 
							:key="payment.value"
							class="payment-item"
							:class="{ active: selectedPayment === payment.value }"
							@click="selectPayment(payment.value)"
						>
							<uni-icons :type="payment.icon" size="20" :color="selectedPayment === payment.value ? '#007aff' : '#666'"></uni-icons>
							<text class="payment-name">{{ payment.name }}</text>
						</view>
					</view>
				</view>
				
				<!-- 订单总价 -->
				<view class="total-section" v-if="selectedTickets.length > 0">
					<view class="total-row">
						<text class="total-label">总价</text>
						<text class="total-price">¥{{ totalPrice }}</text>
					</view>
				</view>
				
				<!-- 操作按钮 -->
				<view class="popup-footer">
					<button class="cancel-btn" @click="close">取消</button>
					<button 
						class="submit-btn" 
						:disabled="!canSubmit"
						@click="createOrder"
						:loading="loading"
					>
						{{ loading ? '创建中...' : '提交订单' }}
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import orderApi from '@/common/api/order.js'

const props = defineProps({
	tickets: {
		type: Array,
		default: () => []
	}
})

const popup = ref(null)
const selectedTickets = ref([]) // 选中的门票ID数组
const ticketQuantities = ref({}) // 门票数量映射 {ticketId: quantity}
const selectedPayment = ref('alipay')
const loading = ref(false)

// 支付方式列表
const paymentMethods = ref([
	{ value: 'alipay', name: '支付宝', icon: 'wallet' },
	{ value: 'wechat', name: '微信支付', icon: 'weixin' },
])

// 计算属性
const availableTickets = computed(() => {
	return props.tickets.filter(ticket => ticket.status === 'active')
})

const totalPrice = computed(() => {
	let total = 0
	selectedTickets.value.forEach(ticketId => {
		const ticket = availableTickets.value.find(t => t.ticketId === ticketId)
		if (ticket) {
			total += ticket.price * getTicketQuantity(ticketId)
		}
	})
	return total
})

const canSubmit = computed(() => {
	return selectedTickets.value.length > 0 && selectedPayment.value
})

// 方法
const open = () => {
	// 检查用户是否登录
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}
	
	// 检查是否有可用门票
	if (availableTickets.value.length === 0) {
		uni.showToast({
			title: '暂无可用门票',
			icon: 'none'
		})
		return
	}
	
	popup.value.open()
}

const close = () => {
	popup.value.close()
	resetForm()
}

// 切换门票选择状态
const toggleTicket = (ticket) => {
	const ticketId = ticket.ticketId
	const index = selectedTickets.value.indexOf(ticketId)
	
	if (index === -1) {
		// 添加门票
		selectedTickets.value.push(ticketId)
		ticketQuantities.value[ticketId] = 1 // 默认数量为1
	} else {
		// 移除门票
		selectedTickets.value.splice(index, 1)
		delete ticketQuantities.value[ticketId]
	}
}

const selectPayment = (payment) => {
	selectedPayment.value = payment
}

// 获取门票数量
const getTicketQuantity = (ticketId) => {
	return ticketQuantities.value[ticketId] || 0
}

// 增加门票数量
const increaseQuantity = (ticketId) => {
	const ticket = availableTickets.value.find(t => t.ticketId === ticketId)
	if (ticket && getTicketQuantity(ticketId) < ticket.stock) {
		ticketQuantities.value[ticketId] = getTicketQuantity(ticketId) + 1
	}
}

// 减少门票数量
const decreaseQuantity = (ticketId) => {
	if (getTicketQuantity(ticketId) > 1) {
		ticketQuantities.value[ticketId] = getTicketQuantity(ticketId) - 1
	}
}

const getTicketTypeName = (type) => {
	const typeMap = {
		'adult': '成人票',
		'child': '儿童票',
		'student': '学生票',
		'elder': '老人票'
	}
	return typeMap[type] || '标准票'
}

const resetForm = () => {
	selectedTickets.value = []
	ticketQuantities.value = {}
	selectedPayment.value = 'alipay'
}

// 创建订单
const createOrder = async () => {
	if (!canSubmit.value) return
	
	loading.value = true
	
	try {
		// 准备订单数据 - 支持多个门票
		const orderData = {
			tickets: selectedTickets.value.map(ticketId => ({
				ticketId: ticketId,
				quantity: getTicketQuantity(ticketId)
			})),
			paymentMethod: selectedPayment.value
		}
		
		console.log('提交订单数据:', orderData)
		
		// 调用创建订单API
		const response = await orderApi.createOrder(orderData)
		
		console.log('订单创建响应:', response)
		
		if (response && (response.code === 200 || response.status === 'success')) {
			uni.showToast({
				title: '订单创建成功',
				icon: 'success'
			})
			
			// 关闭弹窗
			close()
			
			// 如果是支付宝支付，跳转到支付宝支付页面
			if (selectedPayment.value === 'alipay') {
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/orders/alipay?orderId=${response.data.orderId || response.data.id}`
					})
				}, 1500)
			} else {
				// 其他支付方式跳转到订单详情页面
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/orders/orders?orderId=${response.data.orderId || response.data.id}`
					})
				}, 1500)
			}
		} else {
			throw new Error(response?.message || '订单创建失败')
		}
	} catch (error) {
		console.error('创建订单失败:', error)
		uni.showToast({
			title: error.message || '创建订单失败，请重试',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 组件挂载时初始化
onMounted(() => {
	console.log('购买按钮组件已挂载')
})
</script>

<style lang="scss" scoped>
.buy-btn-container {
	.popup-info {
		padding: 40rpx 30rpx 30rpx;
		border-radius: 30rpx 30rpx 0 0;
		background-color: #ffffff;
		max-height: 80vh;
		overflow-y: auto;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		
		.popup-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}
	
	.ticket-section {
		margin-bottom: 30rpx;
		
		.ticket-list {
			display: flex;
			flex-direction: column;
			gap: 20rpx;
		}
		
		.ticket-item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 25rpx;
						border: 2rpx solid #e0e0e0;
						border-radius: 16rpx;
						background-color: #fafafa;
						transition: all 0.3s ease;
						
						&.active {
							border-color: #007aff;
							background-color: #f0f8ff;
							box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);
						}
						
						.ticket-info {
							display: flex;
							flex-direction: column;
							gap: 8rpx;
							flex: 1;
							
							.ticket-name {
								font-size: 32rpx;
								font-weight: 600;
								color: #333;
							}
							
							.ticket-desc {
								font-size: 26rpx;
								color: #666;
							}
						}
						
						.ticket-price {
							display: flex;
							flex-direction: column;
							align-items: flex-end;
							gap: 8rpx;
							margin-right: 20rpx;
							
							.price {
								font-size: 32rpx;
								font-weight: bold;
								color: #e64340;
							}
							
							.stock {
								font-size: 24rpx;
								color: #999;
							}
						}
						
						.ticket-quantity-control {
							display: flex;
							align-items: center;
							gap: 15rpx;
							
							.quantity-btn {
								width: 50rpx;
								height: 50rpx;
								border: 2rpx solid #007aff;
								border-radius: 50%;
								background-color: transparent;
								color: #007aff;
								font-size: 24rpx;
								font-weight: bold;
								
								&:disabled {
									border-color: #ccc;
									color: #ccc;
								}
							}
							
							.quantity-text {
								font-size: 28rpx;
								font-weight: 600;
								color: #333;
								min-width: 60rpx;
								text-align: center;
							}
						}
					}
	}
	
	.quantity-section {
		margin-bottom: 30rpx;
		
		.quantity-control {
			display: flex;
			align-items: center;
			gap: 30rpx;
			
			.quantity-btn {
				width: 60rpx;
				height: 60rpx;
				border: 2rpx solid #007aff;
				border-radius: 50%;
				background-color: transparent;
				color: #007aff;
				font-size: 28rpx;
				font-weight: bold;
				
				&:disabled {
					border-color: #ccc;
					color: #ccc;
				}
			}
			
			.quantity-text {
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
				min-width: 80rpx;
				text-align: center;
			}
		}
	}
	
	.payment-section {
		margin-bottom: 30rpx;
		
		.payment-list {
			display: flex;
			flex-direction: column;
			gap: 20rpx;
		}
		
		.payment-item {
			display: flex;
			align-items: center;
			gap: 20rpx;
			padding: 25rpx;
			border: 2rpx solid #e0e0e0;
			border-radius: 16rpx;
			background-color: #fafafa;
			transition: all 0.3s ease;
			
			&.active {
				border-color: #007aff;
				background-color: #f0f8ff;
			}
			
			.payment-name {
				font-size: 32rpx;
				color: #333;
			}
		}
	}
	
	.total-section {
		margin-bottom: 30rpx;
		padding: 25rpx;
		background-color: #f8f9fa;
		border-radius: 16rpx;
		
		.total-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.total-label {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.total-price {
				font-size: 40rpx;
				font-weight: bold;
				color: #e64340;
			}
		}
	}
	
	.popup-footer {
		display: flex;
		gap: 20rpx;
		
		.cancel-btn {
			flex: 1;
			height: 80rpx;
			border: 2rpx solid #ccc;
			border-radius: 40rpx;
			background-color: transparent;
			color: #666;
			font-size: 32rpx;
		}
		
		.submit-btn {
			flex: 2;
			height: 80rpx;
			background-color: #007aff;
			border-radius: 40rpx;
			color: white;
			font-size: 32rpx;
			font-weight: 600;
			
			&:disabled {
				background-color: #ccc;
				color: #999;
			}
		}
	}
}

.buy-btn {
	width: 200rpx;
	height: 100rpx;
	background-color: #1989fa;
	color: #fff;
	border-radius: 100px;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
	font-weight: 600;
	box-shadow: 0 8rpx 20rpx rgba(25, 137, 250, 0.3);
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.95);
		box-shadow: 0 4rpx 10rpx rgba(25, 137, 250, 0.3);
	}
}

</style>